About 2434 letters

About 12 minutes

#Python's member visibility

You can access object members through object.member:

# Define class class Cat: """ Cat class """ def __init__(self, name: str): """ Constructor Args: name (str): Name """ self.name = name # Create name attribute # Create a group of cats cat1 = Cat("Tom") cat2 = Cat("Happy") cat3 = Cat("San San") # Access name attribute print(cat1.name) print(cat2.name) print(cat3.name) # Modify name attribute cat1.name = 'Schrödinger' print(cat1.name)

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

#Private Members

Private variables can only be accessed by the object that owns them, i.e., they can only be read or modified through the object's own methods. Recall the naming conventions:

  • Private variables use two leading underscores, e.g., __age_of_yukari

Methods can also be made private using this naming style.

For example, to make the cat's name a private attribute, provide a name method to read it and a set_name method to modify it, and forbid naming the cat "Schrödinger":

# Define class class Cat: """ Cat class """ def __init__(self, name: str): """ Constructor Args: name (str): Name """ self.__name = name # Create private __name attribute def name(self) -> str: """ name method to get the cat's name Returns: str: The cat's name """ return self.__name def set_name(self, name: str) -> bool: """ set_name method to set the cat's name Args: name (str): Name to set Returns: bool: Whether setting the name was successful """ if name == "Schrödinger": return False self.__name = name return True # Create object cat = Cat("Garfield") print(cat.name()) # Try to access __name directly try: print('Directly reading __name succeeded:', cat.__name) except Exception as e: print('Directly reading __name failed') # Try setting name to Schrödinger cat.set_name("Schrödinger") print(cat.name())

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

This shows how to control member visibility in Python classes using private attributes and methods.

Created in 5/15/2025

Updated in 5/21/2025